# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from app.monitor_metrics.models.prom_alarm_metrics import PromAlarmMetrics

from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger


__all__ = ['PromAlarmStrategy']

class PromAlarmStrategy(Base, SessionMixin):
    '''
    告警策略
    json字段: https://blog.csdn.net/qq_26373925/article/details/107482924
    '''
    __tablename__ = "prom_alarm_strategy"
    name = Column(String(256), nullable=False, index=True, comment='策略名称')
    # ECS服务器 or k8s容器
    classes = Column(String(128), nullable=False, index=True, comment='策略归类')
    # true/false 使能状态
    state = Column(Boolean, default=text('True'), nullable=False, comment='策略状态')
    # true/false 优先状态， true:比绑定主机组模板中的告警策略-优先. False:与绑定主机组模板中的告警策略-共存，绑定主机模板策略都是False
    priority = Column(Boolean, default=text('False'), nullable=False, comment='策略优先')
    alarm_metrics_uuid = Column(Integer, nullable=False, comment='告警指标的uuid')
    alarm_metrics_parm = Column(JSON, nullable=False, default={}, comment='告警指标的参数')
    # > < == !=
    operator = Column(String(16), nullable=False, comment='运算符')
    value = Column(String(64), nullable=False, comment='告警阀值')
    duration = Column(Integer, nullable=False, default=5, comment='持续分钟')
    notice_count = Column(Integer, nullable=False, comment='告警通知次数')
    # critical:严重(电话部门负责人), major:重要警告(电话告警处理人), warning:一般告警(短信告警处理人),
    # info:提示告警(企业微信告警处理人), nothing:(不告警)
    level = Column(String(16), nullable=False, comment='告警级别')
    labels = Column(JSON, nullable=False, default={}, comment='标签')
    annotations = Column(JSON, nullable=False, default={}, comment='附加信息')
    maintain_begin = Column(DateTime, nullable=True, comment='屏蔽开始时间')
    maintain_end = Column(DateTime, nullable=True, comment='屏蔽结束时间')
    maintain_repeat = Column(Boolean, nullable=True, comment='屏蔽时间是每天')
    callback =Column(String(256), nullable=True, comment='回调接口')
    comment = Column(String(256), nullable=True, comment='告警策略说明')

    template_uuid = Column(Integer, ForeignKey('prom_alarm_template.uuid'), comment='告警模板的uuid')


    __table_args__ = (
        Index('idx_prom_alarm_strategy_name', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<prom_alarm_strategy='{self.name}>"



    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        result["alarm_template"] = self.alarm_template.name
        result["type"] = self.alarm_template.type
        alarm_metrics_object = PromAlarmMetrics.get_object_by_uuid(db, result["alarm_metrics_uuid"])
        if alarm_metrics_object:
            result["alarm_metrics_name"] = alarm_metrics_object.name
        return result



